Closest Binary Search Tree Value

Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.

Note:

  • Given target value is a floating point.
  • You are guaranteed to have only one unique value in the BST that is closest to the target.

Solution:

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. public int closestValue(TreeNode root, double target) {
  12. int closest = root.val;
  13. while (root != null) {
  14. if (Math.abs(root.val - target) < Math.abs(closest - target)) {
  15. closest = root.val;
  16. }
  17. if (target < root.val) {
  18. root = root.left;
  19. } else {
  20. root = root.right;
  21. }
  22. }
  23. return closest;
  24. }
  25. }